﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MarketViewControl.cs" company="">
//   
// </copyright>
// <summary>
//   The market view control.
// </summary>
// --------------------------------------------------------------------------------------------------------------------


using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using Systemathics.FrameWork;
using Systemathics.UserControls.OrderBox;
using Systemathics.UserControls.Properties;

namespace Systemathics.UserControls
{
    [ToolboxBitmap(typeof (MarketViewControl), "UserControlsIcon.bmp")]
    public sealed partial class MarketViewControl : UserControl
    {
        private readonly DataGridViewCellStyle BearStyle;
        private readonly DataGridViewCellStyle BullStyle;
        private readonly DataGridViewCellStyle DownStyle;
        private readonly SynchronizationContext synchronizationContext;
        private readonly SendOrPostCallback pUpdateMarketView;

        private readonly DataGridViewCellStyle UpStyle;
        private Dictionary<Guid, Instrument> marketViewInstruments;
        private int SelectedRowIndex;
        private Guid StrategyId;

        public MarketViewControl()
        {
            InitializeComponent();
            Dock = DockStyle.Fill;

            DoubleBuffered = true;
            UpStyle = new DataGridViewCellStyle {ForeColor = Color.Green, BackColor = Color.WhiteSmoke};
            DownStyle = new DataGridViewCellStyle {ForeColor = Color.Red, BackColor = Color.WhiteSmoke};
            BullStyle = new DataGridViewCellStyle {ForeColor = Color.White, BackColor = Color.LightGreen};
            BearStyle = new DataGridViewCellStyle {ForeColor = Color.White, BackColor = Color.Red};

            synchronizationContext = SynchronizationContext.Current;
            pUpdateMarketView = new SendOrPostCallback(UpdateMarketView);

            Thread.CurrentThread.CurrentCulture = GlobalVariables.SystemathicsCulture();
        }

        public Strategy SelectedStrategy
        {
            set
            {
                marketViewInstruments = value.Instruments;

                if (marketViewInstruments.Count == 1)
                    MarketViewDataGrid.DefaultCellStyle.SelectionBackColor = Color.White;
                StrategyId = value.Id;
                int j = 0;
                lock (MarketViewDataGrid)
                {
                    foreach (KeyValuePair<Guid, Instrument>  kvp in marketViewInstruments)
                    {
                        var i = kvp.Value;
                        InventoryGrid.Rows.Add();
                        var s = i.StaticData.Rules.Tick.ToString("E");
                        var format = "N" + s.Last();
                        InventoryGrid["Instrument_", j].Value = i.StaticData.Name;
                        InventoryGrid["Balance", j].Value = i[Expo.Inventory].Balance;
                        InventoryGrid["BalancePrice", j].Value = i[Expo.Inventory].BalancePrice;
                        InventoryGrid["BalancePrice", j].Style.Format = format;
                        InventoryGrid["Realized", j].Value = i[Expo.Inventory].Realized;
                        InventoryGrid["UnRealized", j].Value = i[Expo.Inventory].UnRealized;
                        InventoryGrid["Fees_", j].Value = - i.StaticData.Fees.TcInventory;
                        InventoryGrid["HasOst", j].Value = i.HasOstToday
                                                               ? Resources.Hors_ligne
                                                               : Resources.En_ligne;
                        InventoryGrid["BuyAllowed", j].Value = i.StaticData.Rules.isBuyAllowed
                                                                   ? Resources.En_ligne
                                                                   : Resources.Hors_ligne;
                        InventoryGrid["SellAllowed", j].Value = i.StaticData.Rules.isSellAllowed
                                                                    ? Resources.En_ligne
                                                                    : Resources.Hors_ligne;
                        InventoryGrid["Shortable", j].Value = i.StaticData.Rules.isShortable
                                                                  ? Resources.En_ligne
                                                                  : Resources.Hors_ligne;
                        InventoryGrid["HardToBorrow", j].Value = i.StaticData.Rules.isHardToBorrow
                                                                     ? Resources.Hors_ligne
                                                                     : Resources.En_ligne;
                        InventoryGrid["Borrow", j].Value = i.StaticData.Fees.Borrow;
                        InventoryGrid["Refi", j].Value = i.StaticData.Refinancing;
                        InventoryGrid["Deposit", j].Value = i.StaticData.Fees.Broker;
                            ////!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                        InventoryGrid["Tick", j].Value = i.StaticData.Rules.Tick;
                        InventoryGrid["TickValue", j].Value = i.StaticData.Rules.TickValue;
                        InventoryGrid["MaxNominalOrder", j].Value = i.StaticData.Rules.MaxNominalOrder;
                        InventoryGrid["Capi", j].Value = i.StaticData.Capitalization;
                        InventoryGrid["Maturity", j].Value = i.StaticData.Maturity;
                        InventoryGrid["Openning", j].Value = i.StaticData.Exchange.Openning;
                        InventoryGrid["OpenAuctions", j].Value = i.StaticData.Exchange.OpenAuctions;
                        InventoryGrid["Closing", j].Value = i.StaticData.Exchange.Closing;
                        InventoryGrid["CloseAuctions", j].Value = i.StaticData.Exchange.CloseAuctions;

                        InventoryGrid["Exchange", j].Value = i.StaticData.Exchange.Place;
                        InventoryGrid["Country", j].Value = i.StaticData.Country;
                        InventoryGrid["Type", j].Value = i.StaticData.Type;
                        InventoryGrid["Class", j].Value = i.StaticData.Classe;

                        MarketViewDataGrid.Rows.Add();
                        MarketViewDataGrid["Id", j].Value = i.Id.ToString();
                        MarketViewDataGrid["State", j].Value = i.StaticData.Rules.isTradable
                                                                   ? Resources.En_ligne
                                                                   : Resources.Hors_ligne;
                        MarketViewDataGrid["Instrument", j].Value = i.StaticData.Name;
                        MarketViewDataGrid["LastTrade", j].Style.Format = format;
                        MarketViewDataGrid["LastTrade", j].Value = i.Trade.Price;
                        MarketViewDataGrid["LastSize", j].Value = i.Trade.Size;
                        MarketViewDataGrid["Var", j].Value = (i.Trade.Price*i.MarketData.Open != 0)
                                                                 ? 100*((i.Trade.Price/i.MarketData.Open) - 1)
                                                                 : 0;
                        MarketViewDataGrid["VWAP", j].Value = i.MarketData.VWAP;
                        MarketViewDataGrid["VWAP", j].Style.Format = format;

                        MarketViewDataGrid["TradedBalance", j].Value = i[Expo.Traded].Balance;
                        MarketViewDataGrid["TradedPrice", j].Style.Format = format;
                        MarketViewDataGrid["TradedPrice", j].Value = i[Expo.Traded].BalancePrice;
                        MarketViewDataGrid["WorkingBalance", j].Value = i[Expo.Working].Balance;
                        MarketViewDataGrid["WorkingPrice", j].Value = i[Expo.Working].BalancePrice;
                        MarketViewDataGrid["WorkingPrice", j].Style.Format = format;

                        MarketViewDataGrid["Fees", j].Value = - i.StaticData.Fees.Tc;
                        MarketViewDataGrid["Unrealized_", j].Value = i[Expo.Traded].UnRealized;
                        MarketViewDataGrid["Realized_", j].Value = i[Expo.Traded].Realized;

                        MarketViewDataGrid["BoughtQty", j].Value = i[Expo.Traded].BoughtQty;
                        MarketViewDataGrid["BoughtPx", j].Value = i[Expo.Traded].BoughtPrice;
                        MarketViewDataGrid["BoughtPx", j].Style.Format = format;
                        MarketViewDataGrid["SoldQty", j].Value = i[Expo.Traded].SoldQty;
                        MarketViewDataGrid["SoldPx", j].Value = i[Expo.Traded].SoldPrice;
                        MarketViewDataGrid["SoldPx", j].Style.Format = format;

                        MarketViewDataGrid["Open", j].Value = i.MarketData.Open;
                        MarketViewDataGrid["High", j].Value = i.MarketData.High;
                        MarketViewDataGrid["Low", j].Value = i.MarketData.Low;
                        MarketViewDataGrid["Close", j].Value = i.MarketData.Close;
                        MarketViewDataGrid["Open", j].Style.Format = format;
                        MarketViewDataGrid["High", j].Style.Format = format;
                        MarketViewDataGrid["Low", j].Style.Format = format;
                        MarketViewDataGrid["Close", j].Style.Format = format;

                        MarketViewDataGrid["Ticker", j].Value = i[i.DataService.Name];
                        MarketViewDataGrid["Sector", j].Value = i.StaticData.Sector;
                        MarketViewDataGrid["Custom1", j].Style.Format = format;
                        MarketViewDataGrid["Custom2", j].Style.Format = format;
                        MarketViewDataGrid["Custom1", j].Value = i.CustomValue1;
                        MarketViewDataGrid["Custom2", j].Value = i.CustomValue2;
                        MarketViewDataGrid["Crncy", j].Value = i.StaticData.Currency.Ticker;
                        MarketViewDataGrid["Ref", j].Value = i.StaticData.Currency.ReferencePrice;
                        j++;
                    }
                }

                while (ParametersGridView.Rows.Count > 0)
                    ParametersGridView.Rows.RemoveAt(0);

                ParametersGridView.Columns.Clear();
                if (value.Params.Count > 0)
                {
                    ParametersGridView.Columns.Add("Instrument", "Instrument");
                    foreach (var column in value.Params.Values.FirstOrDefault().Keys)
                        ParametersGridView.Columns.Add(column, column);
                }

                var l = new List<Object>();
                foreach (var stockparams in value.Params)
                {
                    l.Add(stockparams.Key);
                    l.AddRange(stockparams.Value.Values.ToList());
                    ParametersGridView.Rows.Add(l.ToArray());
                }
            }
        }

        public event EventHandler<FireMessageEventArgs> OnInstrumentSelected;
        public new void Update()
        {
            synchronizationContext.Post(pUpdateMarketView, null);
        }
        public void Clear()
        {
            if (marketViewInstruments != null)
            {
                //marketViewInstruments.Clear();
           
                while (MarketViewDataGrid.Rows.Count > 0)
                    MarketViewDataGrid.Rows.RemoveAt(0);

                while (InventoryGrid.Rows.Count > 0)
                    InventoryGrid.Rows.RemoveAt(0);

                MarketViewDataGrid.Update();
                InventoryGrid.Update();
            }
        }
        private void UpdateMarketView(Object obj)
        {
            for (int i = 0; i < MarketViewDataGrid.Rows.Count; i++)
            {
                var id = Guid.Empty;
                if(MarketViewDataGrid.Rows[i].Cells["Id"].Value != null)
                    id = new Guid(MarketViewDataGrid.Rows[i].Cells["Id"].Value.ToString());
                
                if(marketViewInstruments.ContainsKey(id))
                {
                    var trade = marketViewInstruments[id].Trade.Price;
                    var size = marketViewInstruments[id].Trade.Size; 
                    if(marketViewInstruments[id].StaticData.Classe == AssetClass.Forex)
                    {
                        MarketViewDataGrid.Rows[i].Cells["LastTrade"].Value = (trade == 0) ? marketViewInstruments[id].Blotter[QuoteLevel.One].Mid : trade ;
                        MarketViewDataGrid.Rows[i].Cells["LastSize"].Value = (size == 0) ? Math.Min(marketViewInstruments[id].Blotter[QuoteLevel.One].BidSize, marketViewInstruments[id].Blotter[QuoteLevel.One].AskSize) : size;
                    }
                    else
                    {
                        MarketViewDataGrid.Rows[i].Cells["LastTrade"].Value = trade ;
                        MarketViewDataGrid.Rows[i].Cells["LastSize"].Value = size ;
                    }                    
                    
                    MarketViewDataGrid.Rows[i].Cells["Var"].Value = (marketViewInstruments[id].Trade.Price*marketViewInstruments[id].MarketData.Open != 0)? 100*((marketViewInstruments[id].Trade.Price/marketViewInstruments[id].MarketData.Open) - 1): 0;
                    MarketViewDataGrid.Rows[i].Cells["VWAP"].Value = marketViewInstruments[id].MarketData.VWAP;
                    MarketViewDataGrid.Rows[i].Cells["TradedBalance"].Value = marketViewInstruments[id][Expo.Traded].Balance;
                    MarketViewDataGrid.Rows[i].Cells["TradedPrice"].Value = marketViewInstruments[id][Expo.Traded].BalancePrice;
                    MarketViewDataGrid.Rows[i].Cells["WorkingBalance"].Value = marketViewInstruments[id][Expo.Working].Balance;
                    MarketViewDataGrid.Rows[i].Cells["WorkingPrice"].Value = marketViewInstruments[id][Expo.Working].BalancePrice;
                    MarketViewDataGrid.Rows[i].Cells["Fees"].Value = marketViewInstruments[id].StaticData.Fees.Tc;
                    MarketViewDataGrid.Rows[i].Cells["Unrealized_"].Value = marketViewInstruments[id][Expo.Traded].UnRealized;
                    MarketViewDataGrid.Rows[i].Cells["Realized_"].Value = marketViewInstruments[id][Expo.Traded].Realized;

                    MarketViewDataGrid.Rows[i].Cells["BoughtQty"].Value = marketViewInstruments[id][Expo.Traded].BoughtQty;
                    MarketViewDataGrid.Rows[i].Cells["BoughtPx"].Value = marketViewInstruments[id][Expo.Traded].BoughtPrice;
                    MarketViewDataGrid.Rows[i].Cells["SoldQty"].Value = marketViewInstruments[id][Expo.Traded].SoldQty;
                    MarketViewDataGrid.Rows[i].Cells["SoldPx"].Value = marketViewInstruments[id][Expo.Traded].SoldPrice;

                    MarketViewDataGrid.Rows[i].Cells["Open"].Value = marketViewInstruments[id].MarketData.Open;
                    MarketViewDataGrid.Rows[i].Cells["High"].Value = marketViewInstruments[id].MarketData.High;
                    MarketViewDataGrid.Rows[i].Cells["Low"].Value = (marketViewInstruments[id].MarketData.Low == Decimal.MinusOne)? 0: marketViewInstruments[id].MarketData.Low;
                    MarketViewDataGrid.Rows[i].Cells["Close"].Value = marketViewInstruments[id].MarketData.Close;
                    MarketViewDataGrid.Rows[i].Cells["Custom1"].Value = marketViewInstruments[id].CustomValue1;
                    MarketViewDataGrid.Rows[i].Cells["Custom2"].Value = marketViewInstruments[id].CustomValue2;

                    InventoryGrid.Rows[i].Cells["Balance"].Value = marketViewInstruments[id][Expo.Inventory].Balance;
                    InventoryGrid.Rows[i].Cells["BalancePrice"].Value = marketViewInstruments[id][Expo.Inventory].BalancePrice;
                    InventoryGrid.Rows[i].Cells["Realized"].Value = marketViewInstruments[id][Expo.Inventory].Realized;
                    InventoryGrid.Rows[i].Cells["UnRealized"].Value = marketViewInstruments[id][Expo.Inventory].UnRealized;
                }
            }
        }
        private void MarketViewDataGrid_MouseDown(object sender, MouseEventArgs e)
        {
            DataGridView.HitTestInfo Hti;
            if (e.Button == MouseButtons.Right)
            {
                Hti = MarketViewDataGrid.HitTest(e.X, e.Y);

                if (Hti.Type == DataGridViewHitTestType.Cell)
                {
                    if (MarketViewDataGrid.Rows.Count > 1)
                    {
                        SelectedRowIndex = Hti.RowIndex;
                        OrdersContextMenuStrip.Show(MarketViewDataGrid, new Point(e.X, e.Y));
                        MarketViewDataGrid.Rows[SelectedRowIndex].Selected = true;
                    }
                }
            }
        }
        private void MarketViewDataGrid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (MarketViewDataGrid[e.ColumnIndex, e.RowIndex].Value != null)
            {
                string s = MarketViewDataGrid[e.ColumnIndex, e.RowIndex].OwningColumn.Name;
                if (s == "TargetBalance" || s == "TradedBalance")
                {
                    if ((int) MarketViewDataGrid[e.ColumnIndex, e.RowIndex].Value >= 0)
                        MarketViewDataGrid[e.ColumnIndex, e.RowIndex].Style = UpStyle;
                    else
                        MarketViewDataGrid[e.ColumnIndex, e.RowIndex].Style = DownStyle;
                }

                if (s == "Net P&L")
                {
                    if ((double) MarketViewDataGrid[e.ColumnIndex, e.RowIndex].Value >= 0)
                        MarketViewDataGrid[e.ColumnIndex, e.RowIndex].Style = UpStyle;
                    else
                        MarketViewDataGrid[e.ColumnIndex, e.RowIndex].Style = DownStyle;
                }
                else if (s == "Open" || s == "Close")
                {
                    if (MarketViewDataGrid["Close", e.RowIndex].Value != null && MarketViewDataGrid["Open", e.RowIndex].Value != null)
                    {
                        if ((decimal)MarketViewDataGrid["Close", e.RowIndex].Value == 0)
                        {
                            MarketViewDataGrid["Open", e.RowIndex].Style.ForeColor = Color.Black;
                            MarketViewDataGrid["High", e.RowIndex].Style.ForeColor = Color.Black;
                            MarketViewDataGrid["Low", e.RowIndex].Style.ForeColor = Color.Black;
                            MarketViewDataGrid["Close", e.RowIndex].Style.ForeColor = Color.Black;
                        }
                        else if ((decimal)MarketViewDataGrid["Open", e.RowIndex].Value >= (decimal)MarketViewDataGrid["Close", e.RowIndex].Value)
                        {
                            MarketViewDataGrid["Open", e.RowIndex].Style = UpStyle;
                            MarketViewDataGrid["High", e.RowIndex].Style = UpStyle;
                            MarketViewDataGrid["Low", e.RowIndex].Style = UpStyle;
                            MarketViewDataGrid["Close", e.RowIndex].Style = UpStyle;
                        }
                        else
                        {
                            MarketViewDataGrid["Open", e.RowIndex].Style = DownStyle;
                            MarketViewDataGrid["High", e.RowIndex].Style = DownStyle;
                            MarketViewDataGrid["Low", e.RowIndex].Style = DownStyle;
                            MarketViewDataGrid["Close", e.RowIndex].Style = DownStyle;
                        }
                    }
                }
                else if (s == "Var")
                {
                    var delta = (decimal)MarketViewDataGrid[e.ColumnIndex, e.RowIndex].Value;
                    if (delta >= 2)
                        MarketViewDataGrid[e.ColumnIndex, e.RowIndex].Style = BullStyle;
                    else if (delta >= 0 && delta < 2)
                        MarketViewDataGrid[e.ColumnIndex, e.RowIndex].Style = UpStyle;
                    else if (delta < 0 && delta >= -2)
                        MarketViewDataGrid[e.ColumnIndex, e.RowIndex].Style = DownStyle;
                    else if (delta < -2)
                        MarketViewDataGrid[e.ColumnIndex, e.RowIndex].Style = BearStyle;
                }
            }
        }
        private void MarketViewDataGrid_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.RowIndex > -1 && e.ColumnIndex > -1)
                    if (MarketViewDataGrid[e.ColumnIndex, e.RowIndex].Value != null)
                        OnInstrumentSelected(this, new FireMessageEventArgs(new Guid(MarketViewDataGrid["Id", e.RowIndex].Value.ToString()), DateTime.Now.TimeOfDay));
            }
            catch (Exception)
            {
            }
        }
        private void MarketViewDataGrid_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Down:
                    if (MarketViewDataGrid.CurrentCell.RowIndex < MarketViewDataGrid.RowCount - 1)
                    {
                        MarketViewDataGrid.CurrentCell = MarketViewDataGrid[MarketViewDataGrid.CurrentCell.ColumnIndex, MarketViewDataGrid.CurrentCell.RowIndex + 1];
                        MarketViewDataGrid.Rows[MarketViewDataGrid.CurrentCell.RowIndex].Selected = true;
                        MarketViewDataGrid_CellClick(this, new DataGridViewCellEventArgs(MarketViewDataGrid.CurrentCell.ColumnIndex, MarketViewDataGrid.CurrentCell.RowIndex - 1));
                    }

                    break;
                case Keys.Up:
                    if (MarketViewDataGrid.CurrentCell.RowIndex > 0)
                    {
                        MarketViewDataGrid.CurrentCell = MarketViewDataGrid[MarketViewDataGrid.CurrentCell.ColumnIndex, MarketViewDataGrid.CurrentCell.RowIndex - 1];
                        MarketViewDataGrid.Rows[MarketViewDataGrid.CurrentCell.RowIndex].Selected = true;
                        MarketViewDataGrid_CellClick(this, new DataGridViewCellEventArgs(MarketViewDataGrid.CurrentCell.ColumnIndex, MarketViewDataGrid.CurrentCell.RowIndex + 1));
                    }

                    break;
            }
        }
        private void buyAllowedToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var id = new Guid(MarketViewDataGrid.Rows[SelectedRowIndex].Cells["Id"].Value.ToString());
            marketViewInstruments[id].StaticData.Rules.isBuyAllowed = true;
            InventoryGrid["BuyAllowed", SelectedRowIndex].Value = Resources.En_ligne;
            MarketViewDataGrid.Rows[SelectedRowIndex].Cells["State"].Value =
                marketViewInstruments[id].StaticData.Rules.isTradable ? Resources.En_ligne : Resources.Hors_ligne;
            using (var db = new SystemathicsEntities(GlobalVariables.EntitiesConnectionString()))
            {
                db.DBRules.Where(u => (Guid) u.DBInstrumentsReference.EntityKey.EntityKeyValues[0].Value == id).
                    FirstOrDefault().isBuyAllowed = true;
                db.SaveChanges(true);
            }
        }
        private void buyDisallowedToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var id = new Guid(MarketViewDataGrid.Rows[SelectedRowIndex].Cells["Id"].Value.ToString());
            marketViewInstruments[id].StaticData.Rules.isBuyAllowed = false;
            InventoryGrid["BuyAllowed", SelectedRowIndex].Value = Resources.Hors_ligne;
            MarketViewDataGrid.Rows[SelectedRowIndex].Cells["State"].Value =
                marketViewInstruments[id].StaticData.Rules.isTradable ? Resources.En_ligne : Resources.Hors_ligne;
            using (var db = new SystemathicsEntities(GlobalVariables.EntitiesConnectionString()))
            {
                db.DBRules.Where(u => (Guid) u.DBInstrumentsReference.EntityKey.EntityKeyValues[0].Value == id).
                    FirstOrDefault().isBuyAllowed = false;
                db.SaveChanges(true);
            }
        }
        private void shortAllowedToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var id = new Guid(MarketViewDataGrid.Rows[SelectedRowIndex].Cells["Id"].Value.ToString());
            marketViewInstruments[id].StaticData.Rules.isShortable = true;
            InventoryGrid["Shortable", SelectedRowIndex].Value = Resources.En_ligne;
            MarketViewDataGrid.Rows[SelectedRowIndex].Cells["State"].Value =
                marketViewInstruments[id].StaticData.Rules.isTradable ? Resources.En_ligne : Resources.Hors_ligne;
            using (var db = new SystemathicsEntities(GlobalVariables.EntitiesConnectionString()))
            {
                db.DBRules.Where(u => (Guid) u.DBInstrumentsReference.EntityKey.EntityKeyValues[0].Value == id).
                    FirstOrDefault().isShortable = true;
                db.SaveChanges(true);
            }
        }
        private void shortDisallowedToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var id = new Guid(MarketViewDataGrid.Rows[SelectedRowIndex].Cells["Id"].Value.ToString());
            marketViewInstruments[id].StaticData.Rules.isShortable = false;
            InventoryGrid["Shortable", SelectedRowIndex].Value = Resources.Hors_ligne;
            MarketViewDataGrid.Rows[SelectedRowIndex].Cells["State"].Value =
                marketViewInstruments[id].StaticData.Rules.isTradable ? Resources.En_ligne : Resources.Hors_ligne;
            using (var db = new SystemathicsEntities(GlobalVariables.EntitiesConnectionString()))
            {
                db.DBRules.Where(u => (Guid) u.DBInstrumentsReference.EntityKey.EntityKeyValues[0].Value == id).
                    FirstOrDefault().isShortable = false;
                db.SaveChanges(true);
            }
        }
        private void sellAllowedToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var id = new Guid(MarketViewDataGrid.Rows[SelectedRowIndex].Cells["Id"].Value.ToString());
            marketViewInstruments[id].StaticData.Rules.isSellAllowed = true;
            InventoryGrid["SellAllowed", SelectedRowIndex].Value = Resources.En_ligne;
            MarketViewDataGrid.Rows[SelectedRowIndex].Cells["State"].Value =
                marketViewInstruments[id].StaticData.Rules.isTradable ? Resources.En_ligne : Resources.Hors_ligne;
            using (var db = new SystemathicsEntities(GlobalVariables.EntitiesConnectionString()))
            {
                db.DBRules.Where(u => (Guid) u.DBInstrumentsReference.EntityKey.EntityKeyValues[0].Value == id).
                    FirstOrDefault().isSellAllowed = true;
                db.SaveChanges(true);
            }
        }
        private void sellDisAllowedToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var id = new Guid(MarketViewDataGrid.Rows[SelectedRowIndex].Cells["Id"].Value.ToString());
            marketViewInstruments[id].StaticData.Rules.isSellAllowed = false;
            InventoryGrid["SellAllowed", SelectedRowIndex].Value = Resources.Hors_ligne;
            MarketViewDataGrid.Rows[SelectedRowIndex].Cells["State"].Value =
                marketViewInstruments[id].StaticData.Rules.isTradable ? Resources.En_ligne : Resources.Hors_ligne;
            using (var db = new SystemathicsEntities(GlobalVariables.EntitiesConnectionString()))
            {
                db.DBRules.Where(u => (Guid) u.DBInstrumentsReference.EntityKey.EntityKeyValues[0].Value == id).FirstOrDefault().isSellAllowed = false;
                db.SaveChanges(true);
            }
        }
        private void isHardToBorrowToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var id = new Guid(MarketViewDataGrid.Rows[SelectedRowIndex].Cells["Id"].Value.ToString());
            marketViewInstruments[id].StaticData.Rules.isHardToBorrow = true;
            InventoryGrid["HardToBorrow", SelectedRowIndex].Value = Resources.Hors_ligne;
            MarketViewDataGrid.Rows[SelectedRowIndex].Cells["State"].Value =
                marketViewInstruments[id].StaticData.Rules.isTradable ? Resources.En_ligne : Resources.Hors_ligne;
            using (var db = new SystemathicsEntities(GlobalVariables.EntitiesConnectionString()))
            {
                db.DBRules.Where(u => (Guid) u.DBInstrumentsReference.EntityKey.EntityKeyValues[0].Value == id).FirstOrDefault().isHardToBorrow = true;
                db.SaveChanges(true);
            }
        }
        private void isEasyToBorrowToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var id = new Guid(MarketViewDataGrid.Rows[SelectedRowIndex].Cells["Id"].Value.ToString());
            marketViewInstruments[id].StaticData.Rules.isHardToBorrow = false;
            InventoryGrid["HardToBorrow", SelectedRowIndex].Value = Resources.En_ligne;
            MarketViewDataGrid.Rows[SelectedRowIndex].Cells["State"].Value =
                marketViewInstruments[id].StaticData.Rules.isTradable ? Resources.En_ligne : Resources.Hors_ligne;
            using (var db = new SystemathicsEntities(GlobalVariables.EntitiesConnectionString()))
            {
                db.DBRules.Where(u => (Guid) u.DBInstrumentsReference.EntityKey.EntityKeyValues[0].Value == id).FirstOrDefault().isHardToBorrow = false;
                db.SaveChanges(true);
            }
        }
        private void CancelAll_Click(object sender, EventArgs e)
        {
            var id = new Guid(MarketViewDataGrid.Rows[SelectedRowIndex].Cells["Id"].Value.ToString());
            int cancelledOrders = marketViewInstruments[id].CancelAllOrders();
            new RemotingLogClient().Trace(new FireMessageEventArgs(cancelledOrders + " Orders Canceled for " + marketViewInstruments[id].StaticData.Name, DateTime.Now.TimeOfDay));
        }
        private void CancelAllBuys_Click(object sender, EventArgs e)
        {
            var id = new Guid(MarketViewDataGrid.Rows[SelectedRowIndex].Cells["Id"].Value.ToString());
            int cancelledOrders = marketViewInstruments[id].CancelAllBuyOrders();
            new RemotingLogClient().Trace(
                new FireMessageEventArgs(
                    cancelledOrders + " Orders Canceled for " + marketViewInstruments[id].StaticData.Name, DateTime.Now.TimeOfDay));
        }
        private void CancelAllSells_Click(object sender, EventArgs e)
        {
            var id = new Guid(MarketViewDataGrid.Rows[SelectedRowIndex].Cells["Id"].Value.ToString());
            int cancelledOrders = marketViewInstruments[id].CancelAllSellOrders();
            new RemotingLogClient().Trace(new FireMessageEventArgs(cancelledOrders + " Orders Canceled for " + marketViewInstruments[id].StaticData.Name, DateTime.Now.TimeOfDay));
        }
        private void enableForThisStrategyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var id = new Guid(MarketViewDataGrid.Rows[SelectedRowIndex].Cells["Id"].Value.ToString());
            MarketViewDataGrid.Rows[SelectedRowIndex].Cells["State"].Value = Resources.En_ligne;
            marketViewInstruments[id].StaticData.Rules.isTradable = true;
            MarketViewDataGrid.Rows[SelectedRowIndex].DefaultCellStyle.BackColor = Color.LightGray;
        }
        private void disableForThisStrategToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var id = new Guid(MarketViewDataGrid.Rows[SelectedRowIndex].Cells["Id"].Value.ToString());
            MarketViewDataGrid.Rows[SelectedRowIndex].Cells["State"].Value = Resources.Hors_ligne;
            marketViewInstruments[id].StaticData.Rules.isTradable = false;
            MarketViewDataGrid.Rows[SelectedRowIndex].DefaultCellStyle.BackColor = Color.DarkSeaGreen;
        }
        private void buyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var id = new Guid(MarketViewDataGrid.Rows[SelectedRowIndex].Cells["Id"].Value.ToString());
            var ob = new OrderBoxControl {SideLabel = {Text = "BUY"}, Instrument = marketViewInstruments[id]};
            var frm = new Form {Size = new Size(450,280)};
            ob.Dock = DockStyle.Fill;
            ob.Anchor = AnchorStyles.Right | AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Bottom;
            frm.Controls.Add(ob);
            
            if (frm.ShowDialog() == DialogResult.OK)
            {
                frm.Close();
                marketViewInstruments[id].Buy(ob.Order.Style, ob.Order.TargetPrice, ob.Order.TargetQuantity, ob.Order.Ext, StrategyId);
            }
        }
        private void sellToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var id = new Guid(MarketViewDataGrid.Rows[SelectedRowIndex].Cells["Id"].Value.ToString());
            var ob = new OrderBoxControl { SideLabel = { Text = "SELL" }, Instrument = marketViewInstruments[id] };
            var frm = new Form { Size = new Size(450, 280) };
            ob.Dock = DockStyle.Fill;
            ob.Anchor = AnchorStyles.Right | AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Bottom;
            frm.Controls.Add(ob);

            if (frm.ShowDialog() == DialogResult.OK)
            {
                frm.Close();
                marketViewInstruments[id].Sell(ob.Order.Style, ob.Order.TargetPrice, ob.Order.TargetQuantity, ob.Order.Ext, StrategyId);
            }
        }
        private void flattenTradedToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var id = new Guid(MarketViewDataGrid.Rows[SelectedRowIndex].Cells["Id"].Value.ToString());
            marketViewInstruments[id].SweepToFill(Expo.Traded, StrategyId);
        }
        private void flattenInventoryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var id = new Guid(MarketViewDataGrid.Rows[SelectedRowIndex].Cells["Id"].Value.ToString());
            marketViewInstruments[id].SweepToFill(Expo.Inventory, StrategyId);
        }
        private void flattenAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            flattenTradedToolStripMenuItem_Click(sender, e);
            flattenInventoryToolStripMenuItem_Click(sender, e);
        }
        private void toolStripTextBox1_Validated(object sender, EventArgs e)
        {
            int MaxNominal;
            if (int.TryParse(toolStripTextBox1.Text, out MaxNominal))
            {
                var id = new Guid(MarketViewDataGrid.Rows[SelectedRowIndex].Cells["Id"].Value.ToString());
                marketViewInstruments[id].StaticData.Rules.MaxNominalOrder = MaxNominal;
                InventoryGrid["MaxNominalOrder", SelectedRowIndex].Value = MaxNominal;
                using (var db = new SystemathicsEntities(GlobalVariables.EntitiesConnectionString()))
                {
                    db.DBRules.Where(u => (Guid) u.DBInstrumentsReference.EntityKey.EntityKeyValues[0].Value == id).
                        FirstOrDefault().MaxNominalOrder = MaxNominal;
                    db.SaveChanges(true);
                }
            }
            else
                toolStripTextBox1.Text = "Set Max Nominal Order";
        }
    }
}